package beans.lifecycle;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 简单的动态代理实现
 * <p>
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class SimpleProxy implements InvocationHandler {
    private Object target;

    public SimpleProxy(Object target) {
        this.target = target;
    }

    //创建JDK代理对象
    public Object getProxy() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //模拟拦截逻辑
        System.out.println("代理拦截：目标对象 [" + this.target.getClass().getName() + "], 方法名 [" + method.getName() + "]");
        //调用目标对象的方法
        return method.invoke(target, args);
    }
}
